package com.homework.reflect.bean;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author nmm
 * @date 2024-03-2024/3/28
 * @deriction njm......
 */
public class BeanUtil2 {

    public static void setProperty(Object bean, String propertyName, Object value){
        try {
            PropertyDescriptor propertyDescriptor=new PropertyDescriptor(propertyName,bean.getClass());
            Method writeMethod = propertyDescriptor.getWriteMethod();
            writeMethod.invoke(bean,value);
        } catch (Exception e) {
            throw new RuntimeException("属性值"+propertyName+"不匹配...");
        }
    }

    public static Object getProperty(Object bean, String propertyName){
        try {
            PropertyDescriptor propertyDescriptor=new PropertyDescriptor(propertyName,bean.getClass());
            Method readMethod = propertyDescriptor.getReadMethod();
            Object retValue = readMethod.invoke(bean);
            return  retValue;
        } catch (Exception e) {
            throw new RuntimeException("属性值"+propertyName+"不存在...");
        }
    }

    public static void copyProperties(Object source, Object target){
        try {
            BeanInfo beanInfo= Introspector.getBeanInfo(source.getClass(),Object.class);
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            System.out.println(propertyDescriptors.length);
            for (int i = 0; i < propertyDescriptors.length; i++) {
                String propertyName = propertyDescriptors[i].getName();//拿到当前类对象参数列表(属性)

                Object propertyValue = propertyDescriptors[i].getReadMethod().invoke(source);//获取当前source实例的属性值

                PropertyDescriptor  targetDescriptor=new PropertyDescriptor(propertyName,target.getClass());//创建内省对象(通过拿到的属性名)

                targetDescriptor.getWriteMethod().invoke(target,propertyValue);//调用写方法给目标对象赋值
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}